# Create your models here.
from django.db import models
from django.forms import ModelForm
from django import forms 
from django.conf import settings
from mptt.models import MPTTModel
from mptt.forms import TreeNodeChoiceField

import datetime
from taggit.managers import TaggableManager

# Create your models here.

# taskjuggler stuff
DAYPART_CHOICES = (('morning','morning 9:00-12:00'),
					('mid day','mid day 13:00-15:00'),
					('late afternoon','late afternoon 15:00-18:00'))
class Daypart(models.Model):
	name = models.CharField(max_length=64, choices=DAYPART_CHOICES, default='morning')
	def __unicode__(self):
		if self.name=='morning':
			return '09:00'
		elif self.name=='mid day':
			return '13:00'
		else:
			return '15:00'
	
PROJECTION_CHOICE=(('sloppy','sloppy'),('strict','strict'))
class ProjectScenario(MPTTModel):
	name=models.CharField(max_length=16)
	description=models.CharField(max_length=128)
	projection=models.CharField(max_length=16,choices=PROJECTION_CHOICE,blank=True,null=True)
	minslackrate=models.IntegerField(default=0)
	enabled=models.BooleanField(default=True)
	
	# hiearchy
	parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
	def __unicode__(self):
		return self.name	

CURRENCY_CHOICE=(('USD','USD'),)
class Project (models.Model):
	name = models.CharField(max_length=64)
	description = models.TextField(blank=True)
	start=models.DateField()
	end=models.DateField()
	now=models.DateField(blank=True, null=True)
	timeformat=models.CharField(max_length=32,default='%Y-%m-%d')
	numberformat=models.CharField(max_length=32,default='"-" "" "," "." 1')
	currencyformat=models.CharField(max_length=32, default='"(" ")" "," "." 0')
	currency=models.CharField(max_length=8,default='USD',choices=CURRENCY_CHOICE)
	scenario=models.ForeignKey(ProjectScenario)
	class Meta:
		ordering=['-start','-end']
	def __unicode__(self):
		return self.name

class ProjectSelectForm(forms.Form):
	project_list=forms.ModelChoiceField(Project.objects.order_by('name'))

class WorkLimit(models.Model):
	dailymax=models.CharField(max_length=8,blank=True,null=True)
	dailymin=models.CharField(max_length=8,blank=True,null=True)
	maximum=models.CharField(max_length=8,blank=True,null=True)
	minimum=models.CharField(max_length=8,blank=True,null=True)
	monthlymax=models.CharField(max_length=8, blank=True,null=True)
	monthlymin=models.CharField(max_length=8, blank=True,null=True)
	weeklymax=models.CharField(max_length=8,blank=True,null=True)
	weeklymin=models.CharField(max_length=8,blank=True,null=True)

	def __unicode__(self):
		return '|'.join(['dmax.%s'%self.dailymax,
						'dmin.%s'%self.dailymin,
						'wmax.%s'%self.weeklymax,
						'wmin.%s'%self.weeklymin,
						'mmax.%s'%self.monthlymax,
						'mmin.%s'%self.monthlymin,
						'max.%s'%self.maximum,
						'min.%s'%self.minimum])

class Resource(models.Model):
	first_name = models.CharField(max_length=128)
	last_name = models.CharField(max_length=128)
	
	# work limits
	work_limit=models.ForeignKey(WorkLimit, blank=True, null=True)
	
	# tags, they will be "flags" in reports
	tags = TaggableManager(blank=True)

	class Meta:
		ordering=['last_name','first_name']
	def __unicode__(self):
		return '_'.join([self.first_name, self.last_name,str(self.work_limit.id)])

class TimeOff (models.Model):
	start=models.DateField()
	end=models.DateField(blank=True,null=True)
	memo=models.TextField()
	resource=models.ForeignKey(Resource)
	class Meta:
		ordering=['-start','-end']
	def __unicode__(self):
		return ' - '.join([str(self.start),str(self.end)])
		
class Task (MPTTModel):
	# for which project
	project=models.ForeignKey(Project)
	
	# some time stamps
	created=models.DateField(auto_now_add=True)
	last_modified = models.DateField(auto_now=True)
	
	# name, description
	name=models.CharField(max_length=128)
	description=models.TextField()
	
	# hiearchy
	parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
	full_path = models.CharField(max_length=1024, blank=True,editable=False) # I'll traverse the tree to populate this field

	# tags, they will be "flags" in reports
	tags = TaggableManager(blank=True)
	
	def __unicode__(self):
		return self.name

class AllocateResource(models.Model):
	primary=models.ForeignKey(Resource,related_name='primary')
	alternative=models.ForeignKey(Resource,related_name='alternative',blank=True,null=True)
	
	# for which task
	task=models.ManyToManyField(Task, blank=True, null=True)
	def __unicode__(self):
		return '%s (%s)' %(self.primary, self.alternative)
						
class TaskPeriod(models.Model):
	scenario=models.ForeignKey(ProjectScenario, blank=True, null=True)
	
	# start,end,length,duration,effort
	start=models.DateField(blank=True, null=True)
	max_start=models.DateField(blank=True, null=True)
	min_start=models.DateField(blank=True, null=True)
	
	end=models.DateField(blank=True, null=True)
	max_end=models.DateField(blank=True, null=True)
	min_end=models.DateField(blank=True, null=True)
	
	length=models.CharField(max_length=16,blank=True)
	duration=models.CharField(max_length=16,blank=True)
	effort=models.CharField(max_length=16,blank=True)
	
	# for which task?
	task = models.ForeignKey(Task)
	
	# completion
	complete=models.IntegerField(blank=True,null=True)
	milestone=models.BooleanField(default=False)
		
	def __unicode__(self):
		return '|'.join([str(self.start),str(self.end),str(self.duration)+'(D)',str(self.length)+'(L)',str(self.effort)+'(E)'])
			
DEPENDENCY_TYPE=(('precedes','precedes'),('depends','depends on'))
ON_WHAT_TYPE=(('onstart','on start(start-start)'), ('onend','on end(end-start)'))
class TaskDependency(models.Model):
	type=models.CharField(max_length=32, choices=DEPENDENCY_TYPE)
	from_task=models.ForeignKey(Task, related_name='from_task')
	to_task=models.ForeignKey(Task, related_name='to_task')
	gap_duration=models.CharField(max_length=16,blank=True,null=True)
	gap_length=models.CharField(max_length=16,blank=True,null=True)
	on_what=models.CharField(max_length=16, choices=ON_WHAT_TYPE)
		
	def __unicode__(self):
		return '|'.join([self.from_task.name,self.type,self.to_task.name,self.on_what,self.gap_duration,self.gap_length])

class TaskSelectForm(forms.Form):
	task_list= TreeNodeChoiceField(Task.objects.all())
				
class Booking(models.Model):
	# time stamps
	created=models.DateField(auto_now_add=True)
	when=models.DateField(default=datetime.date.today()) # book for which date
	part_of_day=models.ForeignKey(Daypart) # for which part of the day
	length=models.CharField(max_length=16,default='4h')
	overtime=models.IntegerField(default=1,blank=True,null=True)
	
	task = models.ForeignKey(Task,blank=True,null=True) # for which task
	resource=models.ForeignKey(Resource,blank=True,null=True) # by whom
	
	class Meta:
		ordering=['-when']
	def __unicode__(self):
		return '|'.join([self.task.name, self.resource.__unicode__(), str(self.when), self.part_of_day.name, self.length])
	
	
ALERT_CHOICES=(('green','green'),('red','red'),('yellow','yellow'))	
class Journal(models.Model):
	created = models.DateField(auto_now_add=True)
	booking = models.ForeignKey(Booking)
	summary=models.CharField(max_length=128)
	description=models.TextField()
	memo=models.TextField(blank=True) # can document what impact this has
	alert=models.CharField(max_length=16,choices=ALERT_CHOICES,default='green')
	
	class Meta:
		ordering=['-created']	
	def __unicode__(self):
		return self.summary
		
class UploadFileForm(forms.Form):
	title = forms.CharField(max_length=50)
	file  = forms.FileField()


